package com.hedl.practice.diyJava.network_programming.TCP_programming.utils;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class Handler extends Thread{
    private Socket sock;

    public Handler(Socket sock){
        this.sock = sock;
    }

    @Override
    public void run() {
        try(InputStream input = this.sock.getInputStream()) {
            try(OutputStream output = this.sock.getOutputStream()){
                handle(input,output);
            }
        } catch (Exception e) {
            try{
                this.sock.close();
            } catch (IOException ex) {
            }
            System.out.println("client disconnected.");
        }
        super.run();
    }

    public void handle(InputStream input,OutputStream output) throws IOException {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));
        BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));

        writer.write("hello\n");        //写入字符
        writer.flush();     //刷新流

        for (;;){
            String s = reader.readLine();       //读一行文字
            if (s.equals("bye")){
                writer.write("bye\n");
                writer.flush();
                break;
            }
            writer.write("ok: "+s+"\n");
            writer.flush();
        }
    }
}
